﻿using System;
using System.Drawing;
using System.Windows.Forms;
using Medicalsystem.MCP.FormDesigner.Common;
using Medicalsystem.MCP.FormDesigner.Interface;

namespace Medicalsystem.MCP.FormDesigner
{
    /// <summary>
    /// 容器管理者-用于拥有用户界面控件
    /// </summary>
    public class UIContainerHandler : ContainerHandler
    {
        /// <summary>
        /// 容器管理者
        /// </summary>
        /// <param name="container">控件容器</param>
        /// <param name="parentctrlMngDesign">父级控件管理者</param>
        /// <param name="ModelDesign">关联的模板管理者</param>
        public UIContainerHandler(System.Windows.Forms.Control container, CtrlMngDesign parentctrlMngDesign, ModelDesign ModelDesign)
            : base(container, parentctrlMngDesign, ModelDesign)
        {
            Container.MouseDown += new MouseEventHandler(Container_MouseDown);
            Container.MouseMove += new MouseEventHandler(Container_MouseMove);
            Container.MouseUp += new MouseEventHandler(Container_MouseUp);
            Container.MouseEnter += new EventHandler(Container_MouseEnter);
        }

        private bool _isMouseDown = false;
        private bool _beginDrawControl = false;

        #region 鼠标事件

        private void Container_MouseDown(object sender, MouseEventArgs e)
        {
            try
            {
                _isMouseDown = true;

                //如果选择了新增控件 就绘制新控件
                if (!string.IsNullOrEmpty(SingleList.Instance.ControlName))
                {
                    this._beginDrawControl = true;
                }
                else
                {
                    this._beginDrawControl = false;
                }

                this.Container.Capture = true;
                Cursor.Clip = this.Container.RectangleToScreen(this.Container.ClientRectangle);
                _mouseRect = new Rectangle(e.X, e.Y, 0, 0);
            }
            catch (Exception ex)
            {
                TryCustomException.TransactException(ex);
            }
        }

        private void Container_MouseMove(object sender, MouseEventArgs e)
        {
            try
            {
                if (_isMouseDown)
                {
                    if (_beginDrawControl)
                    {
                        ResizeToRectangle(e.Location, FrameStyle.Thick);
                    }
                    else
                    {
                        ResizeToRectangle(e.Location, FrameStyle.Dashed);
                    }
                }
            }
            catch (Exception ex)
            {
                TryCustomException.TransactException(ex);
            }
        }

        /// <summary>
        /// 鼠标按钮弹起事件需要处理的事务如下：
        /// 如果是绘制新控件（直接添加）
        /// 如果是选取（将所有选取项添加入选取列表，如果选取项为零需要重置某些设计器界面控件显示）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Container_MouseUp(object sender, MouseEventArgs e)
        {
            try
            {
                _isMouseDown = false;
                this.Container.Capture = false;
                Cursor.Clip = Rectangle.Empty;

                //规范化选取区域
                if (_mouseRect.Width < 0)
                {
                    _mouseRect.X += _mouseRect.Width;
                    _mouseRect.Width = Math.Abs(_mouseRect.Width);
                }

                if (_mouseRect.Height < 0)
                {
                    _mouseRect.Y += _mouseRect.Height;
                    _mouseRect.Height = Math.Abs(_mouseRect.Height);
                }

                //begion
                this.Container.SuspendLayout();

                if (_beginDrawControl)
                {
                    AddControl(ControlBuilder.ControlNew(SingleList.Instance.AssemblyName,SingleList.Instance.ControlName, ModelDesign, EDesignModeState.Design), _mouseRect);
                    _mouseRect = Rectangle.Empty;
                    _beginDrawControl = false;
                }
                else
                {
                    foreach (CtrlMngDesign ctrlMngDesign in this.ModelDesign.Controls.Ctrls)
                    {
                        //限制选取的是同一容器控件
                        if ((ctrlMngDesign.ParentContainer.Container == Container) && _mouseRect.IntersectsWith(new Rectangle(ctrlMngDesign.Owner.Location, ctrlMngDesign.Owner.Size)))
                        {
                            this.ModelDesign.SelectListAppend(ctrlMngDesign);
                        }
                    }

                    this.ModelDesign.SelectListAppendEnd();
                    _mouseRect = Rectangle.Empty;

                    //如果选取项为零，需要空置控件属性设置窗口
                    if (this.ModelDesign.SelectList.Count == 0)
                    {
                        //OnDesignEvent();
                        if (this.ParentControlMngDesign != null)
                        {
                            this.ModelDesign.SelectListAppend(this.ParentControlMngDesign);
                            this.ModelDesign.SelectListAppendEnd();
                            this.ParentControlMngDesign.ChildContainerFocused = this;
                            this.ParentControlMngDesign.ParentContainer.Container.Refresh();
                        }
                        else
                        {
                            SingleList.Instance.OnMessageEvent(this.ModelDesign.Owner, MessageType.ModelFocus);
                        }
                    }
                }

                //end
                this.Container.ResumeLayout(false);
                this.Container.PerformLayout();
                this.Container.Refresh();
            }
            catch (Exception ex)
            {
                TryCustomException.TransactException(ex);
            }
        }

        private void Container_MouseEnter(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(SingleList.Instance.ControlName))
            {
                this.Container.Cursor = Cursors.Cross;
            }
            else
            {
                this.Container.Cursor = Cursors.Default;
            }
        }

        /// <summary>
        /// 将控件添加到容器
        /// </summary>
        /// <param name="control">控件</param>
        /// <param name="rect">根据拖动区域设置控件大小</param>
        private void AddControl(System.Windows.Forms.Control control, Rectangle rect)
        {
            try
            {
                CtrlMngDesign ctrlMngDesign = null;

                if (control is ICtrlUI)
                {
                    ctrlMngDesign = new CtrlMngDesign((ICtrlBase)control, this, this.ModelDesign);
                    this.Add(ctrlMngDesign);
                }
                else
                {
                    //组件类控件添加到组件类控件容器
                    ctrlMngDesign = new CtrlMngDesign((ICtrlBase)control, this.ModelDesign.CtrlComContainerHandler, this.ModelDesign);
                    this.ModelDesign.CtrlComContainerHandler.Add(ctrlMngDesign);
                }

                SetControlProperty(ctrlMngDesign, rect);

                //执行外部添加事件
                SingleList.Instance.OnMessageEvent(ctrlMngDesign, MessageType.CreateControl);

                control.Focus();
            }
            catch (Exception ex)
            {
                TryCustomException.TransactException(ex);
            }

            //控件新增后重新初始化鼠标样式
            Container_MouseEnter(this, new EventArgs());
        }

        /// <summary>
        /// 初始化控件时设置其属性
        /// </summary>
        /// <param name="control"></param>
        /// <param name="rect"></param>
        private void SetControlProperty(CtrlMngDesign control, Rectangle rect)
        {
            control.Owner.Location = rect.Location;

            string ctrlName = GetControlName(control.Owner);
            ((ICtrlBase)control.Owner).CtrlID = string.Format("{0}_{1}", ctrlName, System.Guid.NewGuid().ToString());

            if (control.Owner is ICtrlUI)
            {
                ((ICtrlUI)control.Owner).ShowText = ctrlName;
            }

            //根据控件类型确定设置控件Size
            switch (((ICtrlBase)control.Owner).UISizeMode)
            {
                case EUISizeMode.AllowNone:
                case EUISizeMode.Null:
                    break;

                case EUISizeMode.AllowWidth:
                    control.Owner.Width = control.Owner.Size.Width > rect.Size.Width ? control.Owner.Size.Width : rect.Size.Width;
                    control.Owner.BackColor = Color.White;
                    break;
                default:
                    control.Owner.Size = new Size(control.Owner.Size.Width > rect.Size.Width ? control.Owner.Size.Width : rect.Size.Width, control.Owner.Size.Height > rect.Size.Height ? control.Owner.Size.Height : rect.Size.Height);
                    break;
            }
        }

        /// <summary>
        /// 取得控件类型
        /// </summary>
        /// <param name="ctrl"></param>
        /// <returns></returns>
        private string GetControlType(System.Windows.Forms.Control ctrl)
        {
            string strType = ctrl.GetType().ToString();
            string strControlType;
            string[] strArr = strType.Split(".".ToCharArray());

            strControlType = strArr[strArr.Length - 1].Trim();

            return strControlType;
        }

        /// <summary>
        /// 返回控件名称
        /// </summary>
        /// <param name="control"></param>
        /// <returns></returns>
        private string GetControlName(System.Windows.Forms.Control control)
        {
            //这里简单返回控件名，如果需要，可以通过修改这个函数做特殊处理
            return control.GetType().Name;
        }

        #endregion 鼠标事件
    }
}